var express = require('express')
var router = express.Router()
const multer = require('multer');
var sqlobj = require('../db/sql_utils');

// image upload
var stroage = multer.diskStorage({
    destination: function (req, file, cd) {
        cd(null, './public/images') 
    },
    filename: function (req, file, cb) {
        var fileFormat = (file.originalname).split(".");
        // cb(null, `${Date.now()}-${file.originalname}`)
        cb(null, `${Date.now()}.`+fileFormat[fileFormat.length - 1])
    }
})
var upload = multer({ storage: stroage });

router.post('/api/upload', upload.any(), function (req, res, next) {
    console.log(req.files)
    let url = `http://${req.headers.host}/images/${req.files[0].filename}`
    if (!req.files) return res.json({code: 400,message: 'Upload failed'})
    return res.json({code: 200,message: 'Uploaded successfully',url: url})
})
module.exports = router

